package com.business_clean.ui.fragment.main;

import static com.business_clean.app.config.Constant.PAGE_SIZE;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.TimeUtils;
import com.business_clean.R;
import com.business_clean.app.App;
import com.business_clean.app.base.BaseFragment;
import com.business_clean.app.config.Constant;
import com.business_clean.app.uitl.ActivityForwardUtil;
import com.business_clean.app.uitl.ToastUtil;
import com.business_clean.app.weight.dialog.CustomImageViewPagerPopup;
import com.business_clean.app.weight.dialog.CustomImageViewerPopup;
import com.business_clean.app.weight.dialog.PagerDrawerPopup;
import com.business_clean.data.mode.ImageEntity;
import com.business_clean.data.mode.circle.ChatMessage;
import com.business_clean.data.mode.circle.ChatMessageLIst;
import com.business_clean.data.mode.circle.ChatStatEntity;
import com.business_clean.data.mode.login.UserInfo;
import com.business_clean.data.mode.project.ProjectMangerList;
import com.business_clean.databinding.FragmentWorkCircleBinding;
import com.business_clean.ui.activity.PreviewPhotoActivity;
import com.business_clean.ui.adapter.circle.ChatAdapter;
import com.business_clean.viewmodel.request.CircleViewModel;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.ImageViewerPopupView;
import com.lxj.xpopup.interfaces.OnSrcViewUpdateListener;
import com.lxj.xpopup.util.SmartGlideImageLoader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.simple.SimpleBoundaryDecider;

import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import io.reactivex.rxjava3.disposables.Disposable;
import me.hgj.mvvmhelper.ext.LogExtKt;

public class WorkingCircleFragment extends BaseFragment<CircleViewModel, FragmentWorkCircleBinding> {

    private ChatAdapter mAdapter;

    private int page;

    private String latest_record_uuid = "";

    private Disposable disposableTimer;

    private boolean isLazyLoad = false; //是否已经懒加载了


    private String total;//记录下总数量

    @Override
    public void initView(@Nullable Bundle savedInstanceState) {

        mAdapter = new ChatAdapter(getMDatabind().recycler);
        getMDatabind().recycler.setAdapter(mAdapter);

        //设置当前日期 ，如果数据有变动的话，肯定也需要进行更换
        getMDatabind().tvCircleDate.setText(TimeUtils.millis2String(TimeUtils.getNowMills(), "yyyy\nMM/dd"));

        //针对权限做处理 只有管理员跟人事可以切
        if (Constant.ROLE_MANGER || Constant.ROLE_HR) {
            getMDatabind().tvChange.setVisibility(View.VISIBLE);
        } else {
            getMDatabind().tvChange.setVisibility(View.GONE);
        }

        //刷新的设置
        getMDatabind().refreshLayout.setEnableRefresh(false);//必须关闭
        getMDatabind().refreshLayout.setEnableAutoLoadMore(true);//必须关闭
        getMDatabind().refreshLayout.setEnableNestedScroll(false);//必须关闭
        getMDatabind().refreshLayout.setEnableScrollContentWhenLoaded(true);//必须关闭
        getMDatabind().refreshLayout.setScrollBoundaryDecider(new SimpleBoundaryDecider() {
            @Override
            public boolean canLoadMore(View content) {
                return super.canRefresh(content);
            }
        });

    }

    @Override
    public void lazyLoadData() {
        fillTopData();
        createTimer();
        isLazyLoad = true;//记录是否已经懒加载了
    }

    @Override
    public void initObserver() {

        //监听下拉刷新 延迟 1 秒执行
        getMDatabind().refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (!TextUtils.isEmpty(total) && mAdapter.getData().size() >= Integer.parseInt(total)) {
                            return;
                        }
                        addAdapterDate();
                        requestLoad();
                    }
                }, 500);
            }
        });

        //切换项目的同时，去更新朋友圈
        App.appViewModelInstance.getProjectInfo().observe(this, new Observer<ProjectMangerList>() {
            @Override
            public void onChanged(ProjectMangerList projectMangerList) {
                fillTopData();
                if (mAdapter != null && mAdapter.getData().size() > 0) {//清空
                    mAdapter.getData().clear();
                    mAdapter.notifyDataSetChanged();
                }
                requestOne();
            }
        });


        //监听 recycler 的滑动监听
        getMDatabind().recycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    // 当 RecyclerView 停止滑动时 获取当前可见 item 中的最后一位
                    LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                    int firstVisiblePosition = layoutManager.findFirstVisibleItemPosition();
                    int lastVisiblePosition = layoutManager.findLastVisibleItemPosition();
                    int middlePosition = (lastVisiblePosition - firstVisiblePosition) / 2 + firstVisiblePosition;

                    ChatMessage message = mAdapter.getItem(middlePosition); // 根据位置获取中间的 item
                    LogExtKt.logE("当前可见的 item --->" + message.getUser_name(), "");
                    if (message != null && !TextUtils.isEmpty(message.getCreate_time())) {
                        String time = message.getCreate_time().substring(0, message.getCreate_time().indexOf(" "));
                        getMDatabind().tvCircleDate.setText(time.replaceFirst("-", "\n").replaceFirst("-", "/"));
                    }
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
    }

    /**
     * 在这里坚挺到用户滑动到顶部了，在新数据增加之前，先把list 中最后一条数据的内容作为基准 自定义日期
     */
    private void addAdapterDate() {
        if (mAdapter.getData().size() == 0) {
            return;
        }
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setIs_self("3");
        chatMessage.setCreate_time(mAdapter.getData().get(0).getCreate_time());
        //添加数据的时候，把时间增加到现在的数据，最顶部
        mAdapter.addData(0, chatMessage);
        mAdapter.notifyDataSetChanged();
    }

    private void fillTopData() {
        if (App.appViewModelInstance.getUserInfo().getValue() != null) {
            UserInfo userInfo = App.appViewModelInstance.getUserInfo().getValue();
            if (userInfo != null && userInfo.getProject() != null) {
                getMDatabind().llChangeProject.setVisibility(View.VISIBLE);
                getMDatabind().tvProjectName.setText(userInfo.getProject().getProject_short_name());
            }
        }
    }

    @Override
    public void onRequestSuccess() {
        getMViewModel().getChatMessageList().observe(this, new Observer<ChatMessageLIst>() {
            @Override
            public void onChanged(ChatMessageLIst chatMessageLIst) {
                total = chatMessageLIst.getTotal();
                getMDatabind().refreshLayout.finishLoadMore();
                if (chatMessageLIst.getList().size() == 0) {
                    ToastUtil.show("没有更多数据了");
                    if (mAdapter.getData().size() == 0) {
                        mAdapter.setEmptyView(R.layout.item_empty_view);
                    }
                    return;
                }

                Collections.reverse(chatMessageLIst.getList());
                if (page == 1) {
                    mAdapter.setList(chatMessageLIst.getList());
                    // 设置RecyclerView倒序显示
                    getMDatabind().recycler.scrollToPosition(mAdapter.getData().size() - 1);
                } else {
                    mAdapter.addData(0, chatMessageLIst.getList());
                }
                latest_record_uuid = chatMessageLIst.getLatest_record_uuid();

            }
        });

        getMViewModel().getChatStat().observe(this, new Observer<ChatStatEntity>() {
            @Override
            public void onChanged(ChatStatEntity chatStatEntity) {
                getMDatabind().tvCircleDaily.setText(chatStatEntity.getNormal_total() + "\n日常工作");
                getMDatabind().tvCircleForeman.setText(chatStatEntity.getLeader_total() + "\n领班打卡");
                getMDatabind().tvCircleClock.setText(chatStatEntity.getWork_total() + "\n打卡");
            }
        });
    }

    @Override
    public void onBindViewClick() {
        //切换项目
        getMDatabind().llChangeProject.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //针对权限做处理 只有管理员跟人事可以切
                if (Constant.ROLE_MANGER || Constant.ROLE_HR) {
                    new XPopup.Builder(getContext())
                            .asCustom(new PagerDrawerPopup(getMActivity())).show();
                }
            }
        });

        //日期
        getMDatabind().ivCircleFilter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getMDatabind().llChatStatistics.getVisibility() == View.VISIBLE) {
                    getMDatabind().tvCircleDate.setVisibility(View.GONE);
                    getMDatabind().llChatStatistics.setVisibility(View.GONE);
                    getMDatabind().ivCircleFilter.setImageResource(R.mipmap.icon_base_stat);
                } else {
                    getMDatabind().tvCircleDate.setVisibility(View.VISIBLE);
                    getMDatabind().llChatStatistics.setVisibility(View.VISIBLE);
                    getMDatabind().ivCircleFilter.setImageResource(R.mipmap.icon_base_stat_true);
                }
            }
        });

        mAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                if (view.getId() == R.id.iv_item_chat_pic) {
//                    if ("2".equals(mAdapter.getData().get(position).getMessage_type())) {//2是视频
//                        Bundle bundle = new Bundle();
//                        bundle.putString("url", "" + mAdapter.getData().get(position).getMedia_url());
//                        bundle.putBoolean("isVideo", true);
//                        ActivityForwardUtil.startActivity(PreviewPhotoActivity.class, bundle);
//                    } else {
//                        XPopup.fixLongClick(view);
//                        ImageView imageView = view.findViewById(R.id.iv_item_chat_pic);
//                        CustomImageViewerPopup viewerPopup = new CustomImageViewerPopup(getMActivity(), mAdapter.getData().get(position).getMedia_url(), mAdapter.getData().get(position).getOrigin_media_url());
                    //自定义的ImageViewer弹窗需要自己手动设置相应的属性，必须设置的有srcView，url和imageLoader。
//                        viewerPopup.setXPopupImageLoader(new SmartGlideImageLoader());
//                        viewerPopup.isShowSaveButton(false);
//                        viewerPopup.setSrcViewUpdateListener(new OnSrcViewUpdateListener() {//滑动的时候会更新这个
//                            @Override
//                            public void onSrcViewUpdate(@NonNull ImageViewerPopupView popupView, int position) {
//                            }
//                        });
//                        new XPopup.Builder(getContext())
//                                .asCustom(viewerPopup)
//                                .show();

                    new XPopup.Builder(getContext())
                            .asCustom(new CustomImageViewPagerPopup(getMActivity(), getConvertData(mAdapter.getData()), position))
                            .show();
//                    }

                }
            }
        });

    }

    /**
     * 做数据转换
     *
     * @param data
     * @return
     */
    private List<ImageEntity> getConvertData(List<ChatMessage> data) {
        List<ImageEntity> images = new ArrayList<>();
        for (ChatMessage message : data) {
            ImageEntity image = new ImageEntity();
            image.setResouceType(Integer.parseInt(message.getMessage_type()));//数据类型
            if ("2".equals(message.getMessage_type())) {
                image.setVideoUrl(message.getMedia_url());
                image.setVideoCoverUrl(message.getPic_thumb());
            } else {
                image.setPhotoUrl(message.getMedia_url());
                image.setOriginalUrl(message.getOrigin_media_url());
            }
            images.add(image);
        }
        return images;
    }


    @Override
    public void onResume() {
        LogExtKt.logE("onResume", "");
        super.onResume();
        if (isLazyLoad) {
            createTimer();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        closeDisposable();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        closeDisposable();
    }

    private void closeDisposable() {
        if (disposableTimer != null) {
            disposableTimer.dispose();
            disposableTimer = null;
        }
    }

    /**
     * 创建定时期
     */
    private void createTimer() {
        requestData();//先执行 1 次，后续的是 5 秒执行 1 次
//        disposableTimer = Observable.interval(5, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(aLong -> {
//            requestData();
//        });
    }


    private void requestData() {
        page = 1;
        getMViewModel().requestChatStat(TimeUtils.date2String(TimeUtils.getNowDate(), "yyyy-MM-dd"));
        requestOne();
    }

    private void requestOne() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("page", "" + page);
        hashMap.put("size", "" + PAGE_SIZE);
        hashMap.put("project_uuid", "" + App.appViewModelInstance.getProjectInfo().getValue().getUuid());
        getMViewModel().requestChatList(hashMap);
    }

    private void requestLoad() {
        page++;
        // 到达顶部，触发刷新操作
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("page", "" + page);
        hashMap.put("size", "" + PAGE_SIZE);
        hashMap.put("project_uuid", "" + App.appViewModelInstance.getProjectInfo().getValue().getUuid());
        hashMap.put("latest_record_uuid", latest_record_uuid);
        mViewModel.requestChatList(hashMap);
    }
}
